var express = require('express');
var router = express.Router();
var { orderModel, typeModel } = require('../model/order');

const alipaySdk = require('../model/alipay-sdk.js')

const AlipayFormData = require('alipay-sdk/lib/form').default;

var multiparty = require('multiparty')

const axios = require('axios')

router.post('/queryOrder', async (req, res) => {

    let { out_trade_no, trade_no } = req.body
    console.log(out_trade_no, trade_no);

    const formData = new AlipayFormData()
    formData.setMethod('get')
    formData.addField('bizContent', {
        out_trade_no,
        trade_no
    })
    const result = alipaySdk.exec(
        'alipay.trade.query',//统一收单下单并支付页面接口,
        {},//api请求的参数（包含 “公共请求参数”和“业务参数”）
        { formData: formData }// result为可以跳转支付链接的url
    )
    result.then(resData => {
        axios({
            url: resData,
            method: 'get',
        }).then(data => {
            // console.log(data);
            let r = data.data.alipay_trade_query_response
            if (r.code == '10000') {
                switch (r.trade_status) {
                    case 'WAIT_BUYER_PAY':
                        res.send({
                            sucess: true,
                            code: 201,
                            msg: '支付宝有记录，但是没有付款'
                        })
                        break;
                    case 'TRADE_FINISHED':
                        res.send({
                            sucess: true,
                            code: 202,
                            msg: '交易完成，不可以退款'
                        })
                        break;
                    case 'TRADE_SUCCESS':
                        res.send({
                            sucess: true,
                            code: 203,
                            msg: '交易完成，可以退款'
                        })
                        break;
                    case 'TRADE_CLOSED':
                        res.send({
                            sucess: true,
                            code: 204,
                            msg: '交易关闭'
                        })
                        break;

                }
            } else if (r.code === '40004') {
                res.send({
                    msg: '失败'
                })
            }
        }).catch(err => {
            res.send({
                msg: "查询失败"
            })
        })
    })
})


router.post('/payment', async (req, res) => {

    let { orderId, price, title } = req.query
    await orderModel.updateOne({ _id: orderId }, { type: '6721ef7c1febd0eb47f8bff9' })
    const formData = new AlipayFormData()
    formData.setMethod('get')
    formData.addField('returnUrl', "http://localhost:5173/order");
    formData.addField('bizContent', {
        outTradeNo: orderId,//订单号 64个字符以内 可包含字母、数字、下划线、且不能重复
        productCode: "FAST_INSTANT_TRADE_PAY",//销售产品码，与支付宝签约的产品码名称，仅支持FAST_INSTANT_TRADE_PAY
        totalAmount: price,// 订单总金额
        subject: title,// 订单描述
        body: title,// 商品描述
    })
    const result = alipaySdk.exec(
        'alipay.trade.wap.pay',//统一收单下单并支付页面接口,
        {},//api请求的参数（包含 “公共请求参数”和“业务参数”）
        { formData: formData }// result为可以跳转支付链接的url
    )
    console.log(result);

    result.then((resp) => {
        res.send({
            code: 200,
            resp
        })
    })
})

router.post('/add', async (req, res) => {
    let bobk = {
        title: '测试的数据1',
        price: 23,
        num: 2,
        time: '9000',
        type: "6721ef681febd0eb47f8bff7"
    }
    orderModel.create(bobk)
    res.send({
        code: 200
    })
})

router.get("/cate", async (req, res) => {
    let cate = await typeModel.find()
    res.send({
        code: 200,
        cate
    })
})

router.get('/list', async (req, res) => {
    let { id, title } = req.query
    let queryArr = [{}]
    let nexName = new RegExp(title)
    if (id) {
        queryArr.push({ type: id })
    }
    if (title != 'null') {

        queryArr.push({ title: nexName })
    }
    let list = await orderModel.find({ $and: queryArr }).populate('type')
    console.log(list);

    res.send({
        code: 200,
        list
    })
})

//查询单独订单数据
router.get('/OrderList', async (req, res) => {
    let { id } = req.query
    let query = [{}]
    if (id) {
        query.push({ _id: id })
    }
    let list = await orderModel.find({ $and: query }).populate('type')
    let endTime = list[0].time
    let price = list[0].price
    let or_id = list[0]._id
    let num = list[0].num
    let title = list[0].title

    res.send({
        code: 200,
        list,
        endTime,
        price,
        or_id,
        num,
        title
    })
})


//时间到删除对应的订单
router.get("/OrderDel", async (req, res) => {
    let { id } = req.query
    console.log(id);
    await orderModel.deleteOne({ _id: id })
    res.send({
        code: 200
    })
})


//退订的当前数据
router.get("/Unsubscribe", async (req, res) => {
    let { id, nums } = req.query
    let list = await orderModel.find({ _id: id })
    if (nums != 0) {
        if (list[0].num == nums) {
            await orderModel.deleteOne({ _id: id })
        } else {
            let list = await orderModel.find({ _id: id })
            list[0].num -= nums
            list[0].save()
        }
    }
    res.send({
        code: 200,
        list
    })
})


router.get('/use', async (req, res) => {
    let { id } = req.query
    await orderModel.updateOne({ _id: id }, { type: '6721ef891febd0eb47f8bffb' })
    res.send({
        code: 200
    })
})
module.exports = router;
